<script setup lang="ts">
import SingleViewer from '@renderer/components/singleViewer/SingleViewer.vue'
import { inject, onMounted, ref, provide, watch, computed } from 'vue'
import OpBtnContainer from '@renderer/components/singleViewer/components/opBtn/OpBtnContainer.vue'
import {
  aspectType,
  EnumAllViewType,
  EnumOpTypes,
  loadSingleViewType,
  opMsgType
} from '@renderer/components/singleViewer/imgTypes'
import axios from 'axios'
import { ISliceInfo } from '@renderer/components/singleViewer/types'
import { useRouter } from 'vue-router'
import { useViewerStatus } from '@renderer/components/singleViewer/useViewerStatus'
import { useScanStore } from '@renderer/store/pinia/scan'
import { useImageStore } from '@renderer/store/pinia/image'
import DraggableCanvas from '@renderer/views/multiScanSeriesPage/components/ScoutContent/components/DraggableCanvas.vue'

const loadingRef = ref(true)
const imgStore = useImageStore()
const scanStore = useScanStore()
const imgInfo = computed(() => imgStore.imgInfo)
const initSize = ref(false)
const activeImageId = computed(() => scanStore.scanSeriesInfo.getActiveImageId())
const { ioInstance, baseUri, throughGatewayFlag, sendMsg } = inject('pyImgHandlerIo') as any

const phaseInfoRef = ref<any>({
  current: 0,
  total: 1
})


provide('windowId', 'stack')
provide('viewType', EnumAllViewType.stack)
provide('phaseInfo', phaseInfoRef)
provide('activeViewType', EnumAllViewType.stack)
const {
  seriesId,
  imageIds,
  showDrag,
  showOpBtn
} = inject('ids', {
  seriesId: '',
  imageIds: [],
  showDrag: false,
  showOpBtn: true
})
scanStore.scanSeriesInfo.updateActiveImageId(imageIds[0])

const router = useRouter()


const aspectRef = ref()

const setAspect = async (args: aspectType, imageId) => {
  if (!showOpBtn || initSize.value) {
    return
  }
  initSize.value = true
  const { width, height } = args
  // handleAspectChange(width, height)
  aspectRef.value = {
    width,
    height
  }
  scanStore.setImageShowSize(imageId, {
    width,
    height
  })
  await setAspect2Server(imageId)
}

const handleAspectChange = (width: number, height: number) => {

  const msg = {
    viewType: EnumAllViewType.stack,
    opType: 'resize',
    size: {
      [EnumAllViewType.stack]: {
        width: width,
        height: height
      }
    }
  }
  sendMsg(msg)
}


const setAspect2Server = async (imageId) => {
  const msg: loadSingleViewType = {
    viewType: EnumAllViewType.stack,
    opType: EnumOpTypes.setSize,
    size: aspectRef.value,
    imageId
  }
  const prefix = throughGatewayFlag ? `${baseUri}/image/` : `${baseUri}/`
  await axios.post(`${prefix}setSize`, msg)
}


const goMpr = () => {
  router.push({
    name: 'mpr'
  })
}
const go3d = () => {
  router.push({
    name: 'volume'
  })
}

const { viewStatusRef } = useViewerStatus(EnumAllViewType.stack)

const sendFlipMsg = (hor_flip: boolean, ver_flip: boolean) => {
  const msg: opMsgType = {
    viewType: EnumAllViewType.stack,
    opType: 'flip',
    hor_flip,
    ver_flip
  }
  sendMsg(msg)
}

watch(
  viewStatusRef,
  (newVal) => {
    sendFlipMsg(newVal.horFlip, newVal.verFlip)
  },
  {
    deep: true
  }
)

const handleRotate = (rotateSubType: string) => {
  console.log(`rotate, ${rotateSubType}`)
  const msg: opMsgType = {
    viewType: EnumAllViewType.stack,
    opType: 'rotate',
    subOpType: rotateSubType
  }
  sendMsg(msg)
}

const handleReset = (subResetType: string) => {
  const msg: opMsgType = {
    viewType: EnumAllViewType.stack,
    opType: 'reset',
    subOpType: subResetType
  }
  sendMsg(msg)
}
const getImgSrc = (id: number, attr: string) => {
  if (imgInfo.value[id] == null || imgInfo.value[id][attr] == undefined) {
    return ''
  }
  loadingRef.value = false
  return imgInfo.value[id][attr]
}

const toggleActiveId = (id: string) => {
  scanStore.scanSeriesInfo.updateActiveImageId(id)
}

const getSizeClass = (imageId) => {
  if (showOpBtn) {
    return {}
  }
  if (scanStore.imageShowSizeMap.has(imageId)) {
    const size = scanStore.imageShowSizeMap.get(imageId)
    return {
      width: size.width + 'px',
      height: size.height + 'px'
    }
  } else {
    return {}
  }
}


const handleChange = () => {
}
</script>

<template>
  <div class="w-full h-full flex flex-col"
       v-loading="loadingRef" element-loading-text="等待图像中">
    <div class="flex w-full h-full">
      <template
        v-for="imageId in imageIds"
        :key="imageId"
      >
        <div class="flex-1 h-full border-2 relative"
             :class="showOpBtn ? (activeImageId == imageId ? 'border-green-500' : ''): ''"
             @click="toggleActiveId(imageId)"
        >
          <single-viewer
            :image-id="imageId"
            :style="getSizeClass(imageId)"
            :view-type="EnumAllViewType.stack"
            @set-aspect="(args) => setAspect(args as aspectType,imageId)"
            :img-src="getImgSrc(imageId,'imgSrc')"
            :fourCornerInfo="getImgSrc(imageId,'fourCornerInfo')"
            :sliceInfo="getImgSrc(imageId,'sliceInfo')"
          />

          <div class="absolute left-0 top-0 w-full h-full"   v-if="showDrag">
            <draggable-canvas

              @positionChange="handleChange"
              :seriesId="seriesId"
              :canvasId="imageId" />
          </div>

        </div>
      </template>


      <div class="w-[100px] h-full flex flex-col" v-if="showOpBtn">
        <op-btn-container
          v-model:viewStatus="viewStatusRef"
          @rotate="handleRotate"
          @reset="handleReset"
        />
        <el-button @click="goMpr" class="w-full">MPR View</el-button>
        <el-button @click="go3d" class="w-full !ml-0">3D View</el-button>
      </div>
    </div>


  </div>
</template>

<style scoped></style>

